<template>
  <div>
    <a-card :bordered="false" class="table-card">
      <advance-table
        title="  "
        :pagination="{
          current: queryParam.pageNum,
          pageSize: queryParam.pageSize,
          total: total,
          showSizeChanger: true,
          showLessItems: true,
          showQuickJumper: true,
          showTotal: (total, range) =>
            `第 ${range[0]}-${range[1]} 条，总计 ${total} 条`,
          onChange: changeSize,
          onShowSizeChange: onShowSizeChange,
        }"
        tableKey="base-bizMonthDeptDetials-index-table"
        rowKey="id"
        size="middle"
        @refresh="getList"
        :columns="columns"
        :data-source="bizMonthDeptDetialsList"
        :loading="loading"
        :format-conditions="true"
      >
        <span slot="operation" slot-scope="{ text, record }">
          <span v-if="record.edit">
            <a @click="() => save(record.key)"> 保存 </a>
            <a-popconfirm title="确定取消?" @confirm="() => cancel(record.key)">
              <a style="margin-left: 10px"> 取消</a>
            </a-popconfirm>
          </span>
          <span v-else>
            <span v-if="isNotDetails">
              <file-upload
                :fileList="record.fileList"
                @afterUpload="uploadCompleteFile"
                @removeFile="handlerRemoveFile"
                :id="record.id"
              ></file-upload>
            </span>
            <span v-else-if="record.fileUrls">
              <div
                v-for="(item, index) in record.fileUrls.split(',')"
                :key="index"
              >
                <a :href="item" target="_blank">{{
                  record.fileNames.split(",")[index]
                }}</a>
              </div>
            </span>
          </span>
        </span>
        <span slot="rowindex" slot-scope="{ index }">
          {{ index + 1 }}
        </span>
        <span slot="shuoming" slot-scope="{ text, record }">
          <a-textarea
            v-if="record.edit"
            placeholder="输入完成情况"
            :auto-size="{ minRows: 2, maxRows: 5 }"
            :value="text"
            :disabled="!isNotDetails"
            @change="
              (e) => handleChange(e.target.value, record.key, 'shuoming')
            "
          />
          <a
            v-else
            @click="() => edit(record.key)"
            :disabled="editingKey !== ''"
          >
            {{ text || "填写完成情况" }}
          </a>
        </span>
      </advance-table>
      <a-row :gutter="32">
        <a-col :span="22" style="margin: 50px 10px; text-align: center">
          <a-button
            type="primary"
            @click="handleUpdateList"
            v-if="bizMonthDeptDetialsList.length > 0 && isNotDetails"
            >提交填报资料</a-button
          >
        </a-col>
      </a-row>
    </a-card>
  </div>
</template>
<script>
import {
  listBizMonthDeptDetials,
  delBizMonthDeptDetials,
  exportBizMonthDeptDetials,
  batchUpdate,
  updateBizMonthDeptDetials,
} from "@/api/biz/bizMonthDeptDetials";
import { updateBizMonthDept } from "@/api/biz/bizMonthDept";
import {
  addBizAssessToDeptDetailsFile,
  delBizAssessToDeptDetailsFile,
} from "@/api/biz/bizAssessToDeptDetailsFile";
import AdvanceTable from "@/components/pt/table/AdvanceTable";
import FileUpload from "@/components/pt/fileupload/IndexList";
export default {
  name: "BizMonthDeptDetials",
  components: {
    AdvanceTable,
    FileUpload,
  },
  data() {
    return {
      showAddModal: false,
      showEditModal: false,
      // 遮罩层
      loading: false,
      fileList: [],
      // 选中数组
      ids: [],
      // 选中的主键集合
      selectedRowKeys: [],
      // 选中的数据集合
      selectedRows: [],
      isNotDetails: true,
      // 高级搜索 展开/关闭
      advanced: false,
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // label的百分比
      labelCol: { span: 6 },
      // 内容区域的百分比
      wrapperCol: { span: 18 },
      // 月报项目详情表格数据
      bizMonthDeptDetialsList: [],
      cacheData: [],
      editingKey: "",
      open: false,
      // 查询参数
      queryParam: {
        pageNum: 1,
        pageSize: 10,
        userId: undefined,

        deptId: undefined,

        userName: undefined,

        deptName: undefined,
      },
      columns: [
        {
          title: "序号",
          dataIndex: "rowindex",
          ellipsis: true,
          align: "center",
          width: "60px",
          scopedSlots: { customRender: "rowindex" },
        },

        {
          title: "检查类目",
          dataIndex: "leimu",
          ellipsis: true,
          align: "left",
          width: "15%",
        },
        {
          title: "检查项目",
          dataIndex: "projects",
          ellipsis: true,
          align: "left",
          width: "40%",
        },
        {
          title: "完成情况",
          dataIndex: "shuoming",
          ellipsis: true,
          align: "left",
          width: "25%",
          scopedSlots: { customRender: "shuoming" },
        },
        {
          title: "操作",
          dataIndex: "operation",
          align: "left",
          width: "20%",
          ellipsis: true,
          scopedSlots: { customRender: "operation" },
        },
      ],
    };
  },
  created() {},
  methods: {
    getListById(id, isNotDetails) {
      this.queryParam.monthDeptId = id;
      this.getList(isNotDetails);
    },
    handleChange(value, key, column) {
      const newData = [...this.bizMonthDeptDetialsList];
      const target = newData.find((item) => key === item.key);
      if (target) {
        target[column] = value;
        this.bizMonthDeptDetialsList = newData;
      }
    },
    handleUpdateList() {
      batchUpdate(this.bizMonthDeptDetialsList).then((res) => {
        if (res.code === 200) {
          updateBizMonthDept({
            id: this.queryParam.monthDeptId,
            status: "1",
          }).then((res) => {
            this.$message.success("资料提交成功");
            this.$emit("ok");
            this.getListById(this.queryParam.monthDeptId, false);
          });
        }
      });
    },
    uploadCompleteFile(item, items, id) {
      console.log(("item", item, items));
      addBizAssessToDeptDetailsFile({
        assessDeptDetailsId: id,
        fileName: item.fileName,
        fileUrl: item.url,
      }).then((response) => {
        this.$message.success("上传成功", 3);
      });
    },
    handlerRemoveFile(file) {
      console.log("file", file);
      delBizAssessToDeptDetailsFile({
        fileUrl: file.url,
        fileName: file.name,
      }).then((response) => {
        this.$message.success("删除成功", 3);
      });
    },
    /** 查询月报项目详情列表 */
    getList(isNotDetails) {
      this.loading = true;
      this.isNotDetails = isNotDetails;
      listBizMonthDeptDetials(this.queryParam).then((response) => {
        this.bizMonthDeptDetialsList = response.data.list.map((item) => {
          return { ...item, key: item.id };
        });
        this.total = response.data.total;
        this.cacheData = this.bizMonthDeptDetialsList.map((item) => ({
          ...item,
        }));
        this.loading = false;
      });
    },
    edit(key) {
      const newData = [...this.bizMonthDeptDetialsList];
      const target = newData.find((item) => key === item.key);
      this.editingKey = key;
      if (target) {
        target.edit = true;
        this.bizMonthDeptDetialsList = newData;
      }
    },
    save(key) {
      const newData = [...this.bizMonthDeptDetialsList];
      const newCacheData = [...this.cacheData];
      const target = newData.find((item) => key === item.key);
      const targetCache = newCacheData.find((item) => key === item.key);
      if (target && targetCache) {
        delete target.edit;
        this.bizMonthDeptDetialsList = newData;
        Object.assign(targetCache, target);
        this.cacheData = newCacheData;
      }
      this.editingKey = "";
      console.log("save", target);
      updateBizMonthDeptDetials(target).then((res) => {
        this.$message.success("保存成功");
      });
    },
    cancel(key) {
      const newData = [...this.bizMonthDeptDetialsList];
      const target = newData.find((item) => key === item.key);
      this.editingKey = "";
      if (target) {
        Object.assign(
          target,
          this.cacheData.find((item) => key === item.key)
        );
        delete target.edit;
        this.bizMonthDeptDetialsList = newData;
      }
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParam.pageNum = 1;
      this.getList(this.isNotDetails);
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParam = {
        pageNum: 1,
        pageSize: 10,
        userId: undefined,

        deptId: undefined,

        userName: undefined,

        deptName: undefined,
      };
      this.handleQuery();
    },
    /** 翻页操作 */
    onShowSizeChange(current, pageSize) {
      console.log("onShowSizeChange", current);
      this.queryParam.pageSize = pageSize;
      this.getList(this.isNotDetails);
    },
    /** 翻页操作 */
    onSizeChange(current, size) {
      console.log("onSizeChange", current);
      this.queryParam.pageNum = 1;
      this.queryParam.pageSize = size;
      this.getList(this.isNotDetails);
    },
    /** 翻页操作 */
    changeSize(current, pageSize) {
      console.log("changeSize", current);
      this.queryParam.pageNum = current;
      this.queryParam.pageSize = pageSize;
      this.getList(this.isNotDetails);
    },
    /** 翻页操作 */
    onSelectChange(selectedRowKeys, selectedRows) {
      console.log("selectedRowKeys", selectedRowKeys);
      this.selectedRowKeys = selectedRowKeys;
      this.selectedRows = selectedRows;
      this.ids = this.selectedRows.map((item) => item.id);
      this.single = selectedRowKeys.length !== 1;
      this.multiple = !selectedRowKeys.length;
    },
    /** 查询折叠和展开操作 */
    toggleAdvanced() {
      this.advanced = !this.advanced;
    },
    handleAdd() {
      this.showAddModal = true;
      this.$nextTick(() => this.$refs.bizMonthDeptDetialsAddForm.handleAdd());
    },
    handleUpdate(record, ids) {
      this.showEditModal = true;
      this.$nextTick(() =>
        this.$refs.bizMonthDeptDetialsEditForm.handleUpdate(record, ids)
      );
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      var that = this;
      const bizMonthDeptDetialsIds = row.id || this.ids;
      this.$confirm({
        title: "确认删除所选中数据?",
        onOk() {
          return delBizMonthDeptDetials(bizMonthDeptDetialsIds).then(() => {
            that.onSelectChange([], []);
            that.getList();
            that.$message.success("删除成功", 3);
          });
        },
        onCancel() {},
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      var that = this;
      this.$confirm({
        title: "是否确认导出?",
        content: "此操作将导出当前条件下所有数据而非选中数据",
        onOk() {
          return exportBizMonthDeptDetials(that.queryParam).then((response) => {
            that.download(response.msg);
            that.$message.success("导出成功", 3);
          });
        },
        onCancel() {},
      });
    },
  },
};
</script>
